﻿using IPTVRClient.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Windows.Forms;
using System.Collections;
using IPTVRClient.model;
using System.Net;
using System.IO;
using System.Data;
using System.Reflection;
using IPVTRClient.model;

namespace IPTVRClient.Utils
{
    /// <summary>
    /// 公共函数和全局变量定义
    /// </summary>
    class Global
    {
        private static object objlock = new object();

        /// <summary>
        /// 配置参数对象
        /// </summary>
        public static ConfigParam configParam = new ConfigParam();

        /// <summary>
        /// 存储监控区域tag与设备的对应关系
        /// </summary>
        public static Dictionary<int, Device> devCameraTable = new Dictionary<int, Device>();
        

        // 当前登录用户
        private static UserInfo currentUser;

        public static UserInfo CurrentUser
        {
            get { return currentUser; }
            set { currentUser = value; }
        }

        //添加设备信息
        public static void AddDevice(int index, Device dev)
        {
            lock (objlock)
            {
                Global.devCameraTable.Add(index, dev);
            }
        }

        //移除设备信息
        public static void RemoveDevice(int index)
        {
            lock (objlock)
            {
                if(Global.devCameraTable.ContainsKey(index))
                {
                    Global.devCameraTable.Remove(index);
                }
            }
        }

        //根据索引获取设备属性
        public static Device GetDevice(int index)
        {
            lock (objlock)
            {
                return Global.devCameraTable[index];
            }
        }

        //根据索引获取设备数量
        public static int GetDeviceCount()
        {
            lock (objlock)
            {
                return Global.devCameraTable.Count();
            }
        }


        //根据索引获取设备数量
        public static bool ContainsDevice(int index)
        {
            lock (objlock)
            {
                return Global.devCameraTable.ContainsKey(index);
            }
        }

        //根据索引获取设备属性
        public static void ClearDevice()
        {
            lock (objlock)
            {
                Global.devCameraTable.Clear();
            }
        }

        /// <summary>
        /// 读取app.config文件配置信息
        /// </summary>
        public static void readConfig()
        {
            configParam.MysqlIpaddr = ConfigurationManager.AppSettings["mysqlIp"];
            configParam.MysqlPort = Convert.ToInt32(ConfigurationManager.AppSettings["mysqlPort"]);
            configParam.MysqlUserName = ConfigurationManager.AppSettings["mysqlUserName"];
            configParam.MysqlPasswd = ConfigurationManager.AppSettings["mysqlPassword"];
            configParam.MysqlDatabase = ConfigurationManager.AppSettings["mysqlDatabase"];
            configParam.Rate = Convert.ToInt32(ConfigurationManager.AppSettings["rate"]);
            configParam.Channel = Convert.ToInt32(ConfigurationManager.AppSettings["channel"]);
            configParam.Ipaddr = ConfigurationManager.AppSettings["proxyIpaddr"];
            configParam.Port = Convert.ToInt32(ConfigurationManager.AppSettings["proxyPort"]);
            configParam.ScreenNum = Convert.ToInt32(ConfigurationManager.AppSettings["screenNum"]);
            configParam.SelfPara = ConfigurationManager.AppSettings["para"];
        }

        /// <summary>
        /// 设置配置参数
        /// </summary>
        /// <param name="config"></param>
        public static void setConfig(ConfigParam conf)
        {
            // 打开config文件
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            AppSettingsSection app = config.AppSettings;

            app.Settings["mysqlIp"].Value = conf.MysqlIpaddr;
            app.Settings["mysqlPort"].Value = conf.MysqlPort.ToString();
            app.Settings["mysqlUserName"].Value = conf.MysqlUserName;
            app.Settings["mysqlPassword"].Value = conf.MysqlPasswd;
            app.Settings["rate"].Value = conf.Rate.ToString();
            app.Settings["channel"].Value = conf.Channel.ToString();
            app.Settings["proxyIpaddr"].Value = conf.Ipaddr;
            app.Settings["proxyPort"].Value = conf.Port.ToString();
            app.Settings["screenNum"].Value = conf.ScreenNum.ToString();
            app.Settings["para"].Value = conf.SelfPara.ToString();
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

            // 修改内存值
            configParam.MysqlIpaddr = conf.MysqlIpaddr;
            configParam.MysqlPort = conf.MysqlPort;
            configParam.MysqlUserName = conf.MysqlUserName;
            configParam.MysqlPasswd = conf.MysqlPasswd;
            configParam.Channel = conf.Channel;
            configParam.Rate = conf.Rate;
            configParam.Ipaddr = conf.Ipaddr;
            configParam.Port = conf.Port;
            configParam.ScreenNum = conf.ScreenNum;
            configParam.SelfPara = conf.SelfPara;
        }

        public static string GetMysqlConnStr()
        {
            // 存储数据库连接字符串
            StringBuilder sb = new StringBuilder();

            // 数据库名称
            sb.Append("Database='");
            sb.Append(configParam.MysqlDatabase);
            sb.Append("';");

            // 数据库ip地址
            sb.Append("Data Source='");
            sb.Append(configParam.MysqlIpaddr);
            sb.Append("';");

            // 数据库连接端口
            sb.Append("Port='");
            sb.Append(configParam.MysqlPort);
            sb.Append("';");

            // 数据库用户名
            sb.Append("User Id='");
            sb.Append(configParam.MysqlUserName);
            sb.Append("';");

            // 数据库密码
            sb.Append("Password='");
            sb.Append(configParam.MysqlPasswd);
            sb.Append("';");

            // 数据库编码  使用连接池
            sb.Append("charset='utf8' ; pooling=true");
            return sb.ToString();
        }

        /// <summary>
        /// 弹出提示消息框
        /// </summary>
        /// <param name="msg"></param>
        public static void showAlertBox(string msg)
        {
            MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg">提示的消息内容</param>
        /// <param name="type">1 询问框  2 确认框  </param>
        /// <returns></returns>
        public static DialogResult showQuestionMessageBox(string msg, int type)
        {
            if (1 == type)
            {
                return MessageBox.Show(msg, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            else if (2 == type)
            {
                return MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            }
            else
            {
                return MessageBox.Show(msg, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
        }

        /// <summary>
        /// HttpWebRequest http post
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            request.Timeout = 30000;
            request.GetRequestStream().Write(Encoding.UTF8.GetBytes(postDataStr), 0, postDataStr.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// HttpWebRequest http get
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "application/json;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// dataTable 转为实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> TableToEntity<T>(DataTable dt) where T : class, new()
        {
            Type type = typeof(T);
            List<T> list = new List<T>();

            foreach (DataRow row in dt.Rows)
            {
                PropertyInfo[] pArray = type.GetProperties();
                T entity = new T();
                foreach (PropertyInfo p in pArray)
                {
                    if (row[p.Name] is DBNull)
                    {
                        //p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
                        continue;
                    }
                    if (row[p.Name] is Int32)
                    {
                        p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
                        continue;
                    }

                    if (row[p.Name] is Int64)
                    {
                        p.SetValue(entity, Convert.ToInt64(row[p.Name]), null);
                        continue;
                    }

                    if(row[p.Name] != null)
                    {
                        p.SetValue(entity, row[p.Name], null);
                    }
                }
                list.Add(entity);
            }
            return list;
        }

        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static long GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }

        /// <summary>  
        /// 时间戳Timestamp转换成日期  
        /// </summary>  
        /// <param name="timeStamp"></param>  
        /// <returns></returns>  
        public static DateTime GetDateTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(toNow);
            return dtStart.Add(toNow);
        }

        /// <summary>  
        /// 获取时间戳Timestamp    
        /// </summary>  
        /// <param name="dt"></param>  
        /// <returns></returns>  
        public static int GetTimeStamp(DateTime dt)
        {
            DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
            int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds);
            return timeStamp;
        }

        internal static void showQuestionMessageBox(string v)
        {
            throw new NotImplementedException();
        }

        public static string ConvertIntDatetime(double utc)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            startTime = startTime.AddMilliseconds(utc);       
            return startTime.ToString("yyyy-MM-dd HH:mm:ss");

        }

        public static int SplitScreenNum(int index)
        {
            if (0 == index)
            {
                return 1;
            }
            else if (1 == index)
            {
                return 4;
            }
            else if (2 == index)
            {
                return 9;
            }
            else if (3 == index)
            {
                return 16;
            }
            else if (4 == index)
            {
                return 36;
            }
            else if (5 == index)
            {
                return 64;
            }
            else
            {
                return -1;
            }
        }
 
        public static int SplitScreenNumToIndex(int screenNum)
        {
            if (1 == screenNum)
            {
                return 0;
            }
            else if (4 == screenNum)
            {
                return 1;
            }
            else if (9 == screenNum)
            {
                return 2;
            }
            else if (16 == screenNum)
            {
                return 3;
            }
            else if (36 == screenNum)
            {
                return 4;
            }
            else if (64 == screenNum)
            {
                return 5;
            }
            else
            {
                return -1;
            }
        }
    }
}
